package v1

import (
	"gohub/app/models/article"
	"gohub/app/requests"
	"gohub/pkg/helpers"
	"gohub/pkg/response"
	"time"

	"github.com/gin-gonic/gin"
)

type ArticleController struct {
	BaseAPIController
}

func (ctrl *ArticleController) Index(c *gin.Context) {
	request := requests.PageRequest{}
	if ok := requests.Validate(c, &request, requests.Page); !ok {
		return
	}

	list, pager := article.Paginate(c, request.Size)

	// 基于 Article 结构体扩展
	type articleListItem struct {
		article.Article `json:",inline"` // 内嵌Article字段
		ID2             uint64           `json:"_id"`
		//PublishDate     string           `json:"publishDate"`
	}

	formatList := make([]interface{}, len(list))
	for i, item := range list {
		formatList[i] = articleListItem{
			Article: item,
			ID2:     item.ID,
			//PublishDate: item.PublishDate,
		}
	}

	data := map[string]interface{}{
		"list":  formatList,
		"page":  pager.CurrentPage - 1,
		"size":  pager.PerPage,
		"total": pager.TotalCount,
	}
	response.Data(c, data)
}

func (ctrl *ArticleController) GetArticleDetail(c *gin.Context) {
	aid := c.Param("id")
	article := article.Get(aid)
	response.Data(c, article)
}

func (ctrl *ArticleController) CreateArticle(c *gin.Context) {

	// 1. 验证表单
	request := requests.CreateArticleRequest{}
	if ok := requests.Validate(c, &request, requests.CreateArticle); !ok {
		return
	}

	// 2. 验证成功，创建数据
	model := article.Article{
		Title:       request.Title,
		Desc:        request.Desc,
		Content:     request.Content,
		Author:      "Admin",
		PublishDate: helpers.Int64ToString(time.Now().UnixNano() / 1e6),
		Ranking:     1,
	}
	model.Create()
	if model.ID > 0 {
		response.Success(c)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}
